//
//  EditGroupUser.m
//  Bespoke
//
//  Created by Cheng on 12/9/13.
//
//

#import "EditGroupUser.h"
#import "GroupUserCell.h"
#import "GDataXMLNode.h"
#import "RequestAPIFunction.h"

#define SHAREGROUP_API @"http://54.235.166.43/BeSpokeAPI/Group/ShareGroup.php"
#define BORDERTOPHEIGHT 40
#define SCREENHEIGHT 768
#define VIEW_AXIS_X 252
#define VIEW_AXIS_Y 181
#define SCROLLVIEWHEIGHT 240
#define KEYBOARDHEIGHT 360
#define BOARDERHEIGHT 15
#define BORDER_BETWEEN_SCROLLVIEW_AND_ADDBUTTON 10
#define TEXTFIELD_NAME_TAG 100000
#define TEXTFIELD_EMAIL_TAG 200000
#define CELL_TAG 300000

@implementation EditGroupUser
@synthesize Tf_GroupName,Bt_AddAnotherUser,Bt_SaveMyGroup,Bt_DeleteMyGroup;
@synthesize SV_Main,Vw_GroupUserCell,AG_Group,Bt_Cancel, BK_En_object;
@synthesize delegate;

int m_CellAxisY=0;
int m_TagCellMax=1;

-(IBAction)CloseEditGroupUser:(id)sender {
    [delegate uiViewTouched:NO];
}

-(void)EditGroupUser:(AccountGroup *)AccountGroup {
    m_CellAxisY=0;
    m_TagCellMax=1;
    AG_Group = AccountGroup;
    
    if (AccountGroup==nil) {
        
        Vw_GroupUserCell = [[[NSBundle mainBundle] loadNibNamed:@"GroupUserCell" owner:self options:nil] objectAtIndex: 0];//Create GroupUser Cell.
        
        Vw_GroupUserCell.frame = CGRectMake(0, m_CellAxisY, Vw_GroupUserCell.frame.size.width, Vw_GroupUserCell.frame.size.height);
        Vw_GroupUserCell.tag = m_TagCellMax+CELL_TAG;
        Vw_GroupUserCell.Bt_Delete.tag = m_TagCellMax;
        [SV_Main addSubview:Vw_GroupUserCell];
        
        [Vw_GroupUserCell.Bt_Delete addTarget:self action:@selector(DeletePressed:) forControlEvents:UIControlEventTouchUpInside];
        
        m_TagCellMax++;
        m_CellAxisY = m_CellAxisY+Vw_GroupUserCell.frame.size.height+BOARDERHEIGHT;
        
    }
    else
        Tf_GroupName.text = AG_Group.NS_Name;
    
    for (AccountGroupUser *User in AG_Group.UserArray) {
        
        Vw_GroupUserCell = [[[NSBundle mainBundle] loadNibNamed:@"GroupUserCell" owner:self options:nil] objectAtIndex: 0];//Create GroupUser Cell.
        
        Vw_GroupUserCell.frame = CGRectMake(0, m_CellAxisY, Vw_GroupUserCell.frame.size.width, Vw_GroupUserCell.frame.size.height);
        Vw_GroupUserCell.tag = m_TagCellMax+CELL_TAG;
        Vw_GroupUserCell.Bt_Delete.tag = m_TagCellMax;
        Vw_GroupUserCell.Tf_Name.tag = m_TagCellMax+TEXTFIELD_NAME_TAG;
        Vw_GroupUserCell.Tf_Email.tag = m_TagCellMax+TEXTFIELD_EMAIL_TAG;
        
        Vw_GroupUserCell.UserID = User.UserID;
        Vw_GroupUserCell.Tf_Name.text = User.name;
        Vw_GroupUserCell.Tf_Email.text = User.email;
        
        Vw_GroupUserCell.Tf_Name.delegate = self;
        Vw_GroupUserCell.Tf_Email.delegate = self;
        [SV_Main addSubview:Vw_GroupUserCell];
        
        [Vw_GroupUserCell.Bt_Delete addTarget:self action:@selector(DeletePressed:) forControlEvents:UIControlEventTouchUpInside];
        
        m_TagCellMax++;
        m_CellAxisY = m_CellAxisY+Vw_GroupUserCell.frame.size.height+BOARDERHEIGHT;
    }
    
    SV_Main.contentSize = CGSizeMake(0, m_CellAxisY-BOARDERHEIGHT);

    
    [self bringSubviewToFront:Bt_AddAnotherUser];
    if (AG_Group.UserArray.count<4)
        Bt_AddAnotherUser.frame = CGRectMake(Bt_AddAnotherUser.frame.origin.x,
                                             m_CellAxisY+self.SV_Main.frame.origin.y,
                                             Bt_AddAnotherUser.frame.size.width,
                                             Bt_AddAnotherUser.frame.size.height);
}

#pragma mark - Action

- (IBAction)AddAnotherUser:(id)sender {
    
    
    
    Vw_GroupUserCell = [[[NSBundle mainBundle] loadNibNamed:@"GroupUserCell" owner:self options:nil] objectAtIndex: 0];//Create GroupUser Cell.
    
    Vw_GroupUserCell.frame = CGRectMake(0, m_CellAxisY, Vw_GroupUserCell.frame.size.width, Vw_GroupUserCell.frame.size.height);
    Vw_GroupUserCell.tag = m_TagCellMax+CELL_TAG;
    Vw_GroupUserCell.Bt_Delete.tag = m_TagCellMax;
    Vw_GroupUserCell.Tf_Name.tag = m_TagCellMax+TEXTFIELD_NAME_TAG;
    Vw_GroupUserCell.Tf_Email.tag = m_TagCellMax+TEXTFIELD_EMAIL_TAG;
    
    Vw_GroupUserCell.Tf_Name.delegate = self;
    Vw_GroupUserCell.Tf_Email.delegate = self;
    
    
    [Vw_GroupUserCell.Bt_Delete addTarget:self action:@selector(DeletePressed:) forControlEvents:UIControlEventTouchUpInside];
    
    [SV_Main addSubview:Vw_GroupUserCell];
    
    m_TagCellMax++;
    m_CellAxisY = m_CellAxisY+Vw_GroupUserCell.frame.size.height+BOARDERHEIGHT;
    
    //Animation.
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.0];
    [UIView setAnimationBeginsFromCurrentState:YES];
    if (Bt_AddAnotherUser.frame.origin.y<=SV_Main.frame.origin.y+SV_Main.frame.size.height-BORDER_BETWEEN_SCROLLVIEW_AND_ADDBUTTON)
        Bt_AddAnotherUser.frame = CGRectMake(Bt_AddAnotherUser.frame.origin.x,
                                             m_CellAxisY+SV_Main.frame.origin.y-BOARDERHEIGHT+BORDER_BETWEEN_SCROLLVIEW_AND_ADDBUTTON,
                                             Bt_AddAnotherUser.frame.size.width,
                                             Bt_AddAnotherUser.frame.size.height);
    [UIView commitAnimations];
        
    SV_Main.contentSize = CGSizeMake(0, m_CellAxisY-BOARDERHEIGHT);
}

- (void)DeletePressed:(id)sender {
    
    int CellAxisY_TEMP = 0;
    
    //Calculate AXIS_Y.
    for (int i=1; i<[sender tag]; i++) {
        CellAxisY_TEMP = CellAxisY_TEMP+Vw_GroupUserCell.frame.size.height + BOARDERHEIGHT;
    }
    
    for (int i=[sender tag]+1; i<m_TagCellMax; i++) {
        
        //Animation.
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:1.0];
        [UIView setAnimationBeginsFromCurrentState:YES];
        ((GroupUserCell *)[self viewWithTag:i+CELL_TAG]).frame = CGRectMake(0, CellAxisY_TEMP, Vw_GroupUserCell.frame.size.width, Vw_GroupUserCell.frame.size.height);
        [UIView commitAnimations];
        
        //Replace previous cell tag.
        ((GroupUserCell *)[self viewWithTag:i+CELL_TAG]).Bt_Delete.tag=i-1;
        ((GroupUserCell *)[self viewWithTag:i+CELL_TAG]).Tf_Name.tag=i-1+TEXTFIELD_NAME_TAG;
        ((GroupUserCell *)[self viewWithTag:i+CELL_TAG]).Tf_Email.tag=i-1+TEXTFIELD_EMAIL_TAG;
        ((GroupUserCell *)[self viewWithTag:i+CELL_TAG]).tag=i-1+CELL_TAG;
        
        CellAxisY_TEMP = CellAxisY_TEMP+Vw_GroupUserCell.frame.size.height + BOARDERHEIGHT;
        
    }
    
    [[self viewWithTag:[sender tag]+CELL_TAG] removeFromSuperview];
    
    m_TagCellMax--;
    m_CellAxisY = m_CellAxisY - Vw_GroupUserCell.frame.size.height - BOARDERHEIGHT;
    
    SV_Main.contentSize = CGSizeMake(0, m_CellAxisY-BOARDERHEIGHT);
    
    //Dynamic button of Add User.
    [UIView animateWithDuration:1.0
                     animations:^{
                         
                         if (self.SV_Main.frame.size.height>SV_Main.contentSize.height)
                             Bt_AddAnotherUser.frame = CGRectMake(Bt_AddAnotherUser.frame.origin.x,
                                                                  m_CellAxisY+SV_Main.frame.origin.y-BOARDERHEIGHT+BORDER_BETWEEN_SCROLLVIEW_AND_ADDBUTTON,
                                                                  Bt_AddAnotherUser.frame.size.width,
                                                                  Bt_AddAnotherUser.frame.size.height);
                     }
                     completion:^(BOOL finished){ }];
}

- (IBAction)DeleteMyGroup:(id)sender {
    [self Action:@"Delete"];
}

- (IBAction)SaveMyGroup:(id)sender {
    
    [self Action:nil];
}


- (void)Action:(NSString *)NS_Status {
    
    NSMutableString* NS_UserXML = [NSMutableString string];
    NSData *responseData;
    NSString *NS_FirstName;
    
    if ([Tf_GroupName.text isEqualToString:@""]) {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Group Name is empty." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    
    if ([BK_En_object.fullName rangeOfString:@" "].location!=NSNotFound) {
        
        NSRange RangeIndex = [BK_En_object.fullName rangeOfString:@" "];
        NS_FirstName = [BK_En_object.fullName substringWithRange:NSMakeRange(0,RangeIndex.location)];
    }
    else
        NS_FirstName = self.BK_En_object.fullName;
    
    
    if ([NS_Status isEqualToString:@"Delete"])
        responseData =
        [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<ShareGroup UserName=\"%@\" FirstName=\"%@\" GroupID=\"%d\" GroupName=\"%@\" Method=\"Delete\"/>",
                                     BK_En_object.userName,
                                             NS_FirstName,
                                     AG_Group.ID,
                                     AG_Group.NS_Name]
                          urlString:SHAREGROUP_API];
    else {
        for (int i=1; i<m_TagCellMax; i++) {
        
            int UserIDTemp = ((GroupUserCell *)[self viewWithTag:i+CELL_TAG]).UserID;
            NSString *NS_NameTemp = ((GroupUserCell *)[self viewWithTag:i+CELL_TAG]).Tf_Name.text;
            NSString *NS_EmailTemp = ((GroupUserCell *)[self viewWithTag:i+CELL_TAG]).Tf_Email.text;
        
        
            if ((![NS_NameTemp isEqualToString:@""])||(![NS_EmailTemp isEqualToString:@""])) {
            
                //Check Name is empty.
                if ([NS_NameTemp isEqualToString:@""]) {
                    UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"The Name is empty." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                    [AlertView show];
                    return;
                }
                
                //Check Email is empty.
                if ([NS_EmailTemp isEqualToString:@""]) {
                    UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"The Email is empty." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                    [AlertView show];
                    return;
                }
                
                //Check username is or not Email.
                if ([NS_EmailTemp rangeOfString:@"@"].location == NSNotFound) {
                    UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"The Email you entered is incorrect." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                    [AlertView show];
                    return;
                }
            
                if (UserIDTemp==0)
                    [NS_UserXML appendString:[NSString stringWithFormat:@"<User ID=\"\" Name=\"%@\" Email=\"%@\" />",NS_NameTemp,NS_EmailTemp]];
                else
                    [NS_UserXML appendString:[NSString stringWithFormat:@"<User ID=\"%d\" Name=\"%@\" Email=\"%@\" />",UserIDTemp,NS_NameTemp,NS_EmailTemp]];
            
            }
        }
    
        //Create ShareGroup.
        if (AG_Group==nil)
            responseData = 
            [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<ShareGroup UserName=\"%@\" FirstName=\"%@\" GroupID=\"\" GroupName=\"%@\" Method=\"Create\">%@</ShareGroup>",
                                                 BK_En_object.userName,
                                                 NS_FirstName,
                                                 Tf_GroupName.text,
                                                 NS_UserXML]
                                      urlString:SHAREGROUP_API];
        //Modify ShareGroup.
        else if (AG_Group!=nil)
            responseData = 
            [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<ShareGroup UserName=\"%@\" FirstName=\"%@\" GroupID=\"%d\" GroupName=\"%@\" Method=\"Modify\" newName=\"%@\">%@</ShareGroup>",
                                                 BK_En_object.userName,
                                                 NS_FirstName,
                                                 AG_Group.ID,
                                                 AG_Group.NS_Name,
                                                 Tf_GroupName.text,
                                                 NS_UserXML]
                                      urlString:SHAREGROUP_API];
    }
    
    //No Network Connection or time out.
    if (responseData == nil)
        return;
    
    NSError *error;
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:responseData options:0 error:&error];
    
    //Check to upload is success.
    if ([[doc nodesForXPath:@"//ShareGroup" error:&error] count]!=0) {
        NSArray *Array_Users = [doc nodesForXPath:@"//ShareGroup" error:nil];
        
        int GroupID = [[[[Array_Users objectAtIndex:0] attributeForName:@"GroupID"] stringValue] intValue];
        NSString *NS_GroupName = [[[Array_Users objectAtIndex:0] attributeForName:@"GroupName"] stringValue];
        NSString *NS_Status = [[[Array_Users objectAtIndex:0] attributeForName:@"Status"] stringValue];
        
        AG_Group.ID = GroupID;
        AG_Group.NS_Name = NS_GroupName;
        AG_Group.UserArray = [[NSMutableArray alloc] init];
        
        if (AG_Group==nil) {
            NS_Status = @"Create";
            AG_Group = [[AccountGroup alloc] ID:GroupID Name:NS_GroupName];
        }
        
        NSArray *UserElements = [[Array_Users objectAtIndex:0] elementsForName:@"User"];
        
        //Loop into each User Memeber
        for(GDataXMLElement *UserElement in UserElements)
        {
            int UserID = [[[UserElement attributeForName:@"ID"]stringValue] intValue];
            NSString *NS_UserName = [[UserElement attributeForName:@"Name"]stringValue];
            NSString *NS_UserEmail = [[UserElement attributeForName:@"Email"]stringValue];
            
            AccountGroupUser *AGU_ShareGroupUserOB = [[AccountGroupUser alloc]UserID:UserID name:NS_UserName email:NS_UserEmail];
            
            [AG_Group.UserArray addObject:AGU_ShareGroupUserOB];
        }
        
        if ([NS_Status isEqualToString:@"Create"]) {
            
            UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Group was successfully Created." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [AlertView show];
            
            [self.delegate MoveShareCircles:AG_Group Action:@"Create"];
        }
        else if ((AG_Group!=nil)&&([NS_Status isEqualToString:@"Success"])) {
            
            UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Group was successfully modified." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [AlertView show];
            [self.delegate MoveShareCircles:AG_Group Action:@"Modify"];
        }
        else if ([NS_Status isEqualToString:@"Delete"]) {
            
            UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Group was successfully deleted." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [AlertView show];
            [self.delegate MoveShareCircles:AG_Group Action:@"Delete"];
        }
        
    }
    else if ([[doc nodesForXPath:@"//Error" error:&error] count]!=0) {
        NSArray *Array_Error = [doc nodesForXPath:@"//Error" error:nil];
        NSString *NS_Message = [[[Array_Error objectAtIndex:0] attributeForName:@"Message"] stringValue];
        
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:NS_Message delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    if (textField.tag>=TEXTFIELD_EMAIL_TAG+3)
        [self ScrollViewLocation:textField SetTextFieldTag:TEXTFIELD_EMAIL_TAG];
    else if ((textField.tag>=TEXTFIELD_NAME_TAG+3)&&(textField.tag<TEXTFIELD_EMAIL_TAG))
        [self ScrollViewLocation:textField SetTextFieldTag:TEXTFIELD_NAME_TAG];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.0];
    [UIView setAnimationBeginsFromCurrentState:YES];
    SV_Main.frame =CGRectMake(SV_Main.frame.origin.x, SV_Main.frame.origin.y, SV_Main.frame.size.width, SCROLLVIEWHEIGHT);
    [UIView commitAnimations];
    
    //[SV_Main setContentOffset:CGPointMake(0,0) animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if ((textField.returnKeyType==UIReturnKeyNext)&&(textField.tag>=TEXTFIELD_EMAIL_TAG))
        [((UITextField *)[self.SV_Main viewWithTag:TEXTFIELD_NAME_TAG+(textField.tag-TEXTFIELD_EMAIL_TAG)+1]) becomeFirstResponder];
    else if ((textField.returnKeyType==UIReturnKeyNext)&&(textField.tag>=TEXTFIELD_NAME_TAG))
        [((UITextField *)[self.SV_Main viewWithTag:TEXTFIELD_EMAIL_TAG+(textField.tag-TEXTFIELD_NAME_TAG)]) becomeFirstResponder];
    return YES;
}

#pragma mark - ScrollViewLocation Function

- (void)ScrollViewLocation:(UITextField *)textField SetTextFieldTag:(int)TextFieldTag {
    
    float axis_Y;
    
    if (textField.tag>=TEXTFIELD_EMAIL_TAG)
        axis_Y = [self.SV_Main viewWithTag:CELL_TAG+textField.tag-TEXTFIELD_EMAIL_TAG].frame.origin.y;
    else if ((textField.tag>=TEXTFIELD_NAME_TAG)&&(textField.tag<TEXTFIELD_EMAIL_TAG))
        axis_Y = [self.SV_Main viewWithTag:CELL_TAG+textField.tag-TEXTFIELD_NAME_TAG].frame.origin.y;
    
    if (self.SV_Main.frame.size.height==SCROLLVIEWHEIGHT) {
        
        CGPoint scrollPoint = CGPointMake(0.0,
                                          //This Height is between bottom of scrollview and AddAnotherUser button
                                          axis_Y);
        [SV_Main setContentOffset:scrollPoint animated:NO];
    }
    
    self.SV_Main.frame =CGRectMake(self.SV_Main.frame.origin.x, self.SV_Main.frame.origin.y, self.SV_Main.frame.size.width,
                                   self.SV_Main.frame.size.height-(KEYBOARDHEIGHT-(SCREENHEIGHT-self.SV_Main.frame.origin.y-self.SV_Main.frame.size.height-BORDER_BETWEEN_SCROLLVIEW_AND_ADDBUTTON)));
}

@end
